import $API from '@/api/services'
import router from '@/router'
import AUTH from '@/utils/auth'

// 获取网址中的参数
function getUrlVar (key, src) {
  let value = []
  let query = src.split('?')
  if (query[1]) {
    let part = query[1].split('&')
    for (let i = 0; i < part.length; i++) {
      let data = part[i].split('=')
      if (data[0] && data[1]) {
        value[data[0]] = data[1]
      }
    }
    if (value[key]) {
      return value[key]
    } else {
      return ''
    }
  }
}

const app = {
  state: {
    panoId: null,
    panoInfo: null,
    worksData: null,
    adData: null,
    notice: null,
    startPicOrVideo: null,
    loadInfo: null,
    praiseCount: 0,
    themeId: 0, // 皮肤Id
    themeObj: {}, // 皮肤样式对象
    bgMusic: '', // 背景音乐
    barrageData: null, // 弹幕数据
    navGuideData: null, // 一键导览
    hasPermission: false, // 是否有权限
    visibleBarrage: false,
    collected: false, // 收藏状态
    praised: false, // 点赞状态
    isSocket: false,
    socketRoom: '',
    menuData: null,
    navMenu: [],
    btMenu: [],
    sceneList: null,
    sceneGroup: [],
    sceneGroupId: null,
    scenePayData: null,
    firstSceneMusic: null,
    curSceneMusic: null,
    sceneIndex: 0,
    miniMapData: null,
    volume: 0.8,
    scenicSceneInfo: null, // 周边场景
    aerialSceneId: 0,
  },
  actions: {
    // 周边场景数据
    getSceneInfoAct ({ commit }, data) {
      commit('SAVE_SCENIC_INFO', data)
    },
    initData ({ commit }, obj) {
      $API('getPanoInfo', [obj.panoId]).then(res => {
        // console.log(res)
        if (res.code == 100 && res.data.code === -98) {
          // 845定制
          commit('SAVE_PANO_INFO', {})
          setTimeout(() => {
            AUTH.checkLogin(1)
          }, 1000)
        } else if (res.code == 100) {
          // res.data.templatetype = 3
          if ($globalconfig.isHaiMeng) {
            res.data.load_type = 0
            res.data.loadinfo = res.data.pano_load
            res.data.ismultiscreen = true
          }
          // 处理音乐
          if (res.data.templatetype == 11 || res.data.templatetype == 12) {
            res.data.ismobilemusic = 2
            res.data.ispcmusic = 2
          }
          // 过滤空场景组
          res.data.group_scene_list = res.data.group_scene_list.filter(item => (item.scenelist && item.scenelist.length > 0))
          // 获取周边场景数据
          // 景点模板，切换场景获取当前场景的周边场景数据12
          let sceneIdStr = getUrlVar('scene_id', window.location.href)
          if (res.data && res.data.templatetype == 12 && sceneIdStr) {
            let groupList = res.data.group_scene_list
            let sceneScenicInfo = null
            if (groupList && groupList.length > 0) {
              groupList.map(item => {
                if (item.scenelist && item.scenelist.length > 0) {
                  item.scenelist.map(sce => {
                    if (sce.scene_id == sceneIdStr) {
                      sceneScenicInfo = sce
                    }
                  })
                }
              })
            }
            // console.log(sceneScenicInfo)
            commit('SAVE_SCENIC_INFO', sceneScenicInfo)
          }

          // 赋值航拍场景id
          if (res.data.scene_aerial_list && res.data.scene_aerial_list.length > 0) {
            res.data.scene_aerial_list.map(item => {
              if (item.is_aerial) {
                commit('AERIAL_SCENE_ID', item.scene_id)
                // 过滤航拍场景
                if (res.data && res.data.templatetype == 11) {
                  res.data.group_scene_list.map(group => {
                    if (group.scenelist && group.scenelist.length > 0) {
                      group.scenelist = group.scenelist.filter(sce => sce.scene_id != item.scene_id)
                    }
                  })
                }
              }
            })
          }
          commit('SAVE_PANO_INFO', res.data)
          const panoInfo = res.data
          this.dispatch('getScenePayData', { panoId: res.data.pano_id, data: res.data })

          // 需要密码访问
          if (panoInfo.ispass == 1 && !AUTH.getCookie('panokey')) {
            if ($VM.$route.name != 'Permission') {
              if (obj.ovvId) {
                router.push(`/permission?id=${obj.panoId}&ovv=${obj.ovvId}`)
              } else {
                router.push(`/permission?id=${obj.panoId}`)
              }
            }
          } else if (panoInfo.limitdate == -1) {
            // 过期作品
            router.push(`/panoview/${obj.panoId}/invalid`)
          }
        }
      }).then(() => {
        // 如果有token拉取信息
        const token = AUTH.getUserCookie('access_token')
        // console.log(token)
        if (token) {
          this.dispatch('getUserInfo')
          this.dispatch('fetchCartGoods')
          // 获取收藏状态
          this.dispatch('getCollectStatus', token)
        }
      })
    },
    fetchOtherData ({ commit }, panoId) {
      // 菜单
      // this.dispatch('fetchMenuData', panoId)
      // 场景
      // this.dispatch('fetchSceneData', panoId)
      // 小地图
      // this.dispatch('fetchMiniMapData', panoId)
      // 一键导览
      // this.dispatch('fetchNavGuideData', panoId)
      // 广告
      // this.dispatch('fetchAd', panoId)
      // 作品集
      // this.dispatch('fetchAllPano', panoId)
    },
    fetchAllPano ({ commit }, panoId) {
      $API('getAllPano', [panoId]).then(res => {
        if (res.data) {
          commit('GET_ALL_PANO', res.data)
        }
      })
    },
    // 获取一键导览信息
    fetchNavGuideData ({ commit }, panoId) {
      $API('getNavGuide', [panoId]).then(res => {
        if (res.data) {
          commit('SAVE_NAV_GUILDE_DATA', res.data)
        }
      })
    },
    // 获取弹幕数据
    fetchBarrageData ({ commit }, panoId) {
      $API('getBarrage', [panoId]).then(res => {
        if (res.data) {
          commit('SAVE_BARRAGE_DATA', res.data)
        }
      })
    },
    // 添加弹幕
    addBarrage ({ commit }, item) {
      $API('addBarrage', [item]).then(res => {
        if (res.data) {
          this.dispatch('fetchBarrageData', item.panoId)
        }
      })
    },
    // 弹幕切换
    toggleBarrage ({ commit }) {
      commit('TOGGLE_BARRAGE')
    },
    getCollectStatus ({ commit }, token) {
      const panoId = this.getters.panoId
      $API('getCollectStatus', [panoId, token]).then(res => {
        if (res) {
          commit('GET_STATUS', res.data)
        }
      })
    },
    // 作品点赞
    addPraise ({ commit, state }) {
      const panoId = state.panoId
      $API('addPraise', [panoId]).then(res => {
        if (res.data) {
          commit('ADD_PRAISE', res.data)

          let userId = 0
          if (this.getters && this.getters.userInfo) {
            userId = this.getters.userInfo.user_id
          }

          AUTH.setCookie('praisecount', panoId + '|' + userId, 24 * 60)
          $VM.$vgo.tip('点赞成功!', 'success')
        }
      })
    },
    // 收藏作品
    addCollection ({ commit, state }) {
      const panoId = state.panoId
      $API('addCollect', [panoId]).then(res => {
        if (res.data) {
          let msg
          if (res.data == '1') {
            msg = '取消收藏'
          }
          if (res.data == '100') {
            msg = '收藏成功'
          }
          AUTH.setCookie('collection', res.data)
          $VM.$vgo.tip(msg, 'success')
          commit('GET_STATUS', { praised: 0, iscollect: res.data == 1 ? false : true })
        }
      })
    },
    // 获取用户数据
    sendCustomInfo ({ commit }, userData) {
      $API('getCustomInfo', [userData])
    },
    fetchAd ({ commit }, panoId) {
      $API('getAd', [panoId]).then(res => {
        if (res.data) {
          commit('FETCH_PANO_AD', res.data)
        }
      })
    },
    getSubscribeStatus ({ commit, state }) {
      let openId = ''
      if (this.getters && this.getters.userInfo) {
        openId = this.getters.userInfo.wx_openid
      }
      if (!openId) return
      $API('getSubscribe', [openId]).then(res => {
        // 1 未关注
        if (res.data !== 1) {
          $VM.$router.push('/subscribe/' + state.panoId)
        }
      })
    },
    fetchOverviewLoadInfo ({ commit }, data) {
      console.log('store app loadinfo')
      commit('SAVE_LOAD_INFO', data)
    },
    clearLoadInfo ({ commit }) {
      commit('CLEAR_LOAD_INFO')
    },
    setAdShowTime ({ commit }, opts) {
      const { panoId, adid, adtype } = opts
      $API('setAdShowTime', [panoId, adid, adtype]).then(res => {

      })
    },
    setAdClickTime ({ commit }, opts) {
      const { panoId, adid, adtype } = opts
      $API('setAdClickTime', [panoId, adid, adtype]).then(res => {

      })
    },
    fetchMiniMapData ({ commit }, panoId) {
      $API('getMiniMaps', [panoId]).then(res => {
        if (res.data) {
          commit('SAVE_MINI_MAP', res.data)
        }
      })
    },
    fetchSceneData ({ commit }, panoId) {
      this.dispatch('getScenePayData', { panoId: panoId })
    },
    getCurSceneList ({ commit }, obj) {
      commit('GET_CUR_SCENE_LIST', obj)
    },
    getCurSceneMusic ({ commit }, url) {
      commit('GET_CUR_SCENE_MUSIC', url)
    },
    // 场景付款
    scenePay ({ commit, state }, opts) {
      $API('payOrder', [opts]).then(res => {
        if (res) {
          if (res.data) {
            const openid = (this.getters && this.getters.userInfo) ? this.getters.userInfo.wx_openid : ''
            let payUrl = `${res.data}&pano_id=${this.getters.panoId}&openid=${openid}`

            window.location.href = payUrl
            return
          } else {
            $VM.$vgo.emit('scenepay:success', opts.productid)
          }
        }
      }).catch(() => {
        $VM.$vgo.emit('scenepay:failed')
      })
    },
    // 解锁
    unlockScene ({ commit }, sceneId) {
      commit('UNLOCK_SCENE', sceneId)
    },
    // 付费场景
    getScenePayData ({ commit, state }, data) {
      // console.log(data)
      $API('getScenePay', [data.panoId]).then(res => {
        // console.log(res)
        if (res.code == 100) {
          let scene
          if (data.data) {
            scene = data.data.group_scene_list
          } else {
            scene = state.panoInfo.group_scene_list
          }
          commit('SAVE_SCENE_PAY_DATA', { payScene: res.data, scene: scene })
        }
      })
    },
    // 清空数据
    clearAppInfo ({ commit }) {
      console.log('清空数据------')
      commit('CLEAR_APP_INFO')
    },
    // 设置导航菜单的new显示隐藏
    setNavmenuNew ({ commit, state }, obj) {
      let arr = JSON.parse(JSON.stringify(state.navMenu || []))
      if (obj.level == 0) {
        // 一级菜单
        arr.map(item => {
          if (item.id == obj.id) {
            item.is_menu_watch = true
          }
        })
      } else if (obj.level == 1) {
        // 二级菜单
        arr.map(item => {
          if (item.children && item.children.length) {
            item.children.map(child => {
              if (child.id == obj.id) {
                child.is_menu_watch = true
              }
            })
          }
        })
        // 所有二级菜单都点击过，把对应的父级菜单置为true
        arr.map(item => {
          let count = 0
          if (item.children && item.children.length) {
            item.children.map(child => {
              if (child.is_menu_watch) {
                count += 1
              }
            })
            if (count === item.children.length) {
              item.is_menu_watch = true
            }
          }
        })
      } else if (obj.level == -1) {
        // -1特殊处理
        arr.map(item => {
          if (item.id == obj.id) {
            item.is_menu_watch = true
          }
          if (item.children && item.children.length) {
            item.children.map(child => {
              if (child.id == obj.id) {
                child.is_menu_watch = true
              }
            })
          }
        })
      }
      commit('SAVE_NAV_MENU', arr)
    },
    // 设置底部菜单的new显示隐藏
    setBottommenuNew ({ commit, state }, obj) {
      let arr = JSON.parse(JSON.stringify(state.btMenu || []))
      arr.map(item => {
        if (item.menu_id == obj.id) {
          item.is_menu_watch = true
        }
      })
      commit('SAVE_BOTTOM_MENU', arr)
    },
  },
  mutations: {
    // 导航菜单
    SAVE_NAV_MENU: (state, data) => {
      state.navMenu = data
      state.menuData.navmenu = data
    },
    // 底部菜单
    SAVE_BOTTOM_MENU: (state, data) => {
      state.btMenu = data
      state.menuData.bottommenu = data
    },
    // 周边场景数据
    SAVE_SCENIC_INFO: (state, data) => {
      state.scenicSceneInfo = data
    },
    UNLOCK_SCENE: (state, sceneId) => {
      // console.log(sceneId)
      // console.log(state.panoId)
      if (state.panoId == sceneId) {
        // console.log('全部付费')
        // console.log(state.sceneGroup)
        state.sceneGroup.map((i, ix) => {
          if (i.scenelist && i.scenelist.length > 0) {
            i.scenelist.map(j => {
              j.isLock = 0
            })
            $VM.$set(state.sceneGroup, ix, i)
          }
        })
        state.sceneList.map((item, index) => {
          item.isLock = 0
          $VM.$set(state.sceneList, index, item)
        })
      } else {
        // console.log('单个付费')
        // console.log(state.sceneList)
        state.sceneList.map((item, index) => {
          // console.log(index)
          if (item.scene_id == sceneId) {
            item.isLock = 0
            $VM.$set(state.sceneList, index, item)
          }
        })
      }

    },
    SAVE_SCENE_PAY_DATA: (state, data) => {
      // 底部付费场景
      state.scenePayData = data.payScene
      let dataGroupScene = data.scene
      // 有付费场景
      if (dataGroupScene) {
        let sceneGroup = []
        dataGroupScene.map(item => {
          if (item.scenelist && item.scenelist.length) {
            // 过滤分组
            item.scenelist.map(i => {
              if (data.payScene && data.payScene.scenelist.length) {
                i.isLock = 0
                data.payScene.scenelist.map(p => {
                  if (p.fk_scene_id == i.scene_id) {
                    i.isLock = 1
                  }
                })
              } else {
                i.isLock = 0
              }
            })
            sceneGroup.push(item)
          }
        })
        // console.log(sceneGroup)
        state.sceneGroup = sceneGroup
        const getFirstScene = () => {
          let groupSce = dataGroupScene[state.sceneIndex]
          if (!dataGroupScene[state.sceneIndex]) {
            groupSce = dataGroupScene[0]
          }
          state.sceneList = groupSce.scenelist || []
          state.curSceneMusic = ((groupSce.scenelist[0] && groupSce.scenelist[0].background_music_url) ? groupSce.scenelist[0].full_background_music_url : '')
        }
        let sceneIdStr = getUrlVar('scene_id', window.location.href)
        if (sceneIdStr) {
          // url中有scene_id
          // 返回当前场景音乐
          let sceneMusic = ''
          for (let j in dataGroupScene) {
            if (dataGroupScene[j].scenelist) {
              let scenelistChild = dataGroupScene[j].scenelist
              for (let k in scenelistChild) {
                if (scenelistChild[k].scene_id == sceneIdStr) {
                  if (scenelistChild[k].background_music_url) {
                    sceneMusic = scenelistChild[k].full_background_music_url
                  }
                  break
                }
              }
            }
          }
          state.curSceneMusic = sceneMusic
          // 返回当前组的场景
          let sceneCurId = 0
          for (let j in dataGroupScene) {
            if (dataGroupScene[j].scenelist) {
              let scenelistChild = dataGroupScene[j].scenelist
              for (let k in scenelistChild) {
                if (scenelistChild[k].scene_id == sceneIdStr) {
                  sceneCurId = j
                  break
                }
              }
            }
          }
          if (sceneCurId) {
            state.sceneList = dataGroupScene[sceneCurId].scenelist
          }
        } else {
          // 重置为0
          state.sceneIndex = 0
          if (dataGroupScene[state.sceneIndex].scenelist.length) {
            getFirstScene()
          } else {
            state.sceneIndex++
            getFirstScene()
          }
          state.sceneIndex = 0
        }
      }
    },
    SAVE_PANO_INFO: (state, data) => {
      state.panoInfo = data

      if (JSON.stringify(data) === '{}') return

      state.panoId = data.pano_id
      // state.loadInfo = data.pano_load
      state.loadInfo = data.loadinfo
      if (data.load_type == 1) {
        state.loadInfo = {
          load_type: data.load_type,
          fk_userpano_load_id: data.fk_userpano_load_id,
        }
      } else {
        if (data.loadinfo) {
          state.loadInfo.load_type = data.load_type
          state.loadInfo.fk_userpano_load_id = data.fk_userpano_load_id
        }
      }

      state.praiseCount = data.praisecount
      state.themeId = data.templatetype
      if (data.templatestyle && data.templatestyle != '') {
        state.themeObj = data.templatestyle
      } else {
        state.themeObj = ''
      }
      state.notice = data.rollfont ? data.rollfont : null
      // 右上角菜单
      state.menuData = data.menu_items
      state.navMenu = data.menu_items.navmenu
      state.btMenu = data.menu_items.bottommenu
      // 音量
      state.volume = data.volume || 0.2
      // 小地图数据列表
      state.miniMapData = data.map_list
      // 一键导览
      state.navGuideData = data.nav_list
      // 广告
      if (data.ad_items) {
        const { pano_ad_list, union_ad_list } = data.ad_items
        pano_ad_list.map(it => {
          it.type = 0
          if (it.adimglink) {
            it.adimglink = it.adimglink.replace('s_', '')
          }
          if (it.full_adimg_link) {
            it.full_adimg_link = it.full_adimg_link.replace('s_', '')
          }
        })
        union_ad_list.map(it => {
          it.type = 1
          if (it.adimglink) {
            it.adimglink = it.adimglink.replace('s_', '')
          }
          if (it.full_adimg_link) {
            it.full_adimg_link = it.full_adimg_link.replace('s_', '')
          }
        })
        state.adData = data.ad_items
      }
      // 作品集
      state.worksData = data.full_integration_group_list

      // 是否需要密码访问
      state.hasPermission = data.ispass == 1 ? false : true

      // 开场提示图片/视频处理
      state.startPicOrVideo = data.full_startpic_url || ''

      // 背景音乐处理
      // let bgUrl = ''
      // // 兼容老版本处理
      // if (data.bgmusicurl && data.bgmusicurl.indexOf('|')) {
      //   bgUrl = data.bgmusicurl.split('|')[1]
      // }

      // if (bgUrl && bgUrl.indexOf('http') == -1) {
      //   bgUrl = $globalconfig.URLS.API + bgUrl
      // }
      if (data.background_music_url) {
        state.bgMusic = data.full_background_music_url
      }
    },
    SAVE_LOAD_INFO: (state, loadData) => {
      console.log(loadData)
      state.loadInfo = loadData
    },
    CLEAR_LOAD_INFO: (state) => {
      state.loadInfo = null
    },
    GET_ALL_PANO: (state, data) => {
      state.worksData = data
    },
    SAVE_NAV_GUILDE_DATA: (state, data) => {
      state.navGuideData = data
    },
    SAVE_BARRAGE_DATA: (state, data) => {
      state.barrageData = data
    },
    ADD_PRAISE: (state, count) => {
      state.praiseCount = count
    },
    TOGGLE_BARRAGE: (state) => {
      state.visibleBarrage = !state.visibleBarrage
    },
    FETCH_PANO_AD: (state, data) => {
      const { panoadlist, unionadlist } = data
      panoadlist.map(it => {
        it.type = 0
        if (it.adimglink) {
          it.adimglink = it.adimglink.replace('s_', '')
        }
        if (it.full_adimg_link) {
          it.full_adimg_link = it.full_adimg_link.replace('s_', '')
        }
      })
      unionadlist.map(it => {
        it.type = 1
        if (it.adimglink) {
          it.adimglink = it.adimglink.replace('s_', '')
        }
        if (it.full_adimg_link) {
          it.full_adimg_link = it.full_adimg_link.replace('s_', '')
        }
      })
      console.log(data)
      state.adData = data
    },
    GET_STATUS: (state, data) => {
      state.collected = data.iscollect
      state.praised = data.praise
    },
    SET_SOCKET: (state, flag) => {
      state.isSocket = flag
    },

    SET_SOCKET_ROOM: (state, number) => {
      state.socketRoom = number
    },
    GET_CUR_SCENE_LIST: (state, obj) => {
      // console.log('2----------')
      state.sceneList = obj.data
      state.sceneGroupId = obj.groupId
    },
    GET_CUR_SCENE_MUSIC: (state, url) => {
      state.curSceneMusic = url
    },
    SAVE_MINI_MAP: (state, data) => {
      state.miniMapData = data
    },
    AERIAL_SCENE_ID: (state, id) => {
      state.aerialSceneId = id
    },
    // 清空数据
    CLEAR_APP_INFO: (state) => {
      state = {
        panoId: null,
        panoInfo: null,
        worksData: null,
        adData: null,
        notice: null,
        startPicOrVideo: null,
        loadInfo: null,
        praiseCount: 0,
        themeId: 0, // 皮肤Id
        themeObj: {}, // 皮肤样式对象
        bgMusic: '', // 背景音乐
        barrageData: null, // 弹幕数据
        navGuideData: null, // 一键导览
        hasPermission: false, // 是否有权限
        visibleBarrage: false,
        collected: false, // 收藏状态
        praised: false, // 点赞状态
        isSocket: false,
        socketRoom: '',
        menuData: null,
        navMenu: [],
        btMenu: [],
        sceneList: null,
        sceneGroup: [],
        sceneGroupId: null,
        scenePayData: null,
        firstSceneMusic: null,
        curSceneMusic: null,
        sceneIndex: 0,
        miniMapData: null,
        volume: 0.8,
        scenicSceneInfo: null,
        aerialSceneId: 0,
      }
    },

  }
}

export default app
